package edu.wit.common.utils.ftp;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Properties;

public class DownloadFtpFile {
    private static  FTPClient ftp = null;

    public static void getEventPicture(HttpServletResponse response,String imgPath) {

        InputStream in = null;
        OutputStream os = null;

        try {
            ftp = initFTP();
            //下载文件 FTP协议里面，规定文件名编码为iso-8859-1，所以读取时要将文件名转码为iso-8859-1
            //如果没有设置按照UTF-8读，获取的流是空值null
            in = ftp.retrieveFileStream(new String(imgPath.getBytes("UTF-8"), "iso-8859-1"));
            String picType = imgPath.split("\\.")[1];
            BufferedImage bufImg = null;
            bufImg = ImageIO.read(in);
            os = response.getOutputStream();
            ImageIO.write(bufImg, picType, os);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(in!=null) {
                try {
                    in.close();
                    destroy();
                } catch (IOException e) {
                }
            }
        }
    }

    //通过读取ftp.properties文件来初始化ftp的参数
    private static FTPClient initFTP() throws IOException {
        InputStream in = DownloadFtpFile.class.getResourceAsStream("/ftp.properties");
        Properties properties = new Properties();
        properties.load(in);
        //url
        String addr = properties.getProperty("ftp_url");
        //端口号
        //Integer.valueOf(properties.getProperty("ftp_port")).intValue();
        int port = Integer.parseInt(properties.getProperty("ftp_port"));
        //用户名密码
        String username = properties.getProperty("ftp_username");
        String password = properties.getProperty("ftp_password");
        //String ftpPath = properties.getProperty("ftp_path");

        ftp = new FTPClient();
        ftp.connect(addr,port);
        ftp.login(username,password);
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftp.setControlEncoding("GBK");
        ftp.setBufferSize(1024*1024*10); //设置缓冲区上传速度为10M，默认为1K
        ftp.setFileType(FTP.BINARY_FILE_TYPE);//设置上传方式位字节
        ftp.enterLocalPassiveMode();//Switch to passive mode
        return ftp;
    }

    //关闭FTP客户端
    private static void destroy() throws IOException {
        if(DownloadFtpFile.ftp != null){
            DownloadFtpFile.ftp.disconnect();
            DownloadFtpFile.ftp = null;
        }
    }
}
